package com.live.qn.stream.widget;

import android.content.Context;
import android.opengl.GLSurfaceView;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;

public class CameraPreviewFrameView extends GLSurfaceView {

    private Listener mListener;
    private ScaleGestureDetector mScaleDetector;
    private GestureDetector mGestureDetector;

    /**
     * 事件对象
     */
    public interface Listener {
        boolean onSingleTapUp(MotionEvent e);

        boolean onZoomValueChanged(float factor);
    }

    public CameraPreviewFrameView(Context context) {
        super(context);
        initialize(context);
    }

    public CameraPreviewFrameView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialize(context);
    }

    /**
     * 配置外部的点击事件
     *
     * @param listener Listener
     */
    public void setListener(Listener listener) {
        mListener = listener;
    }

    /**
     * 缩放的事件处理
     */
    private ScaleGestureDetector.SimpleOnScaleGestureListener simpleOnScaleGestureListener = new ScaleGestureDetector.SimpleOnScaleGestureListener() {

        private float mScaleFactor = 1.0f;

        @Override
        public boolean onScaleBegin(ScaleGestureDetector detector) {
            return true;
        }

        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            // factor > 1, zoom
            // factor < 1, pinch
            mScaleFactor *= detector.getScaleFactor();

            // Don't let the object get too small or too large.
            mScaleFactor = Math.max(0.01f, Math.min(mScaleFactor, 1.0f));

            return mListener != null && mListener.onZoomValueChanged(mScaleFactor);
        }
    };

    /**
     * 手势事件
     */
    private GestureDetector.SimpleOnGestureListener simpleOnGestureListener = new GestureDetector.SimpleOnGestureListener() {

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            if (mListener != null) {
                mListener.onSingleTapUp(e);
            }
            return false;
        }

    };

    /**
     * 初始化
     */
    private void initialize(Context context) {
        mScaleDetector = new ScaleGestureDetector(context, simpleOnScaleGestureListener);
        mGestureDetector = new GestureDetector(context, simpleOnGestureListener);
    }
}
